using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;

using KLATencor.CommonApp.Infrastructure.StateMachine;

namespace StateMachine_Graphical_Editor.Utils
{
    /// <summary>
    /// Data Structure that holds for each state all of the transitions that the state is their target state 
    /// </summary>
    public class InGoingTransitionDS
    {
        #region Members:

        private static InGoingTransitionDS instance = new InGoingTransitionDS();

        /// <summary>
        /// Holds the states' transitions in machine.
        /// <para>Contains pairs of: (State, Transition List of all entering transitions to the state key)</para>
        /// </summary>
        private Hashtable transitionDictionary; //<State, Transition List>

        #endregion

        #region Singelton Definitions:

        private InGoingTransitionDS()
        {
            transitionDictionary = new Hashtable();
        }

        public static InGoingTransitionDS getDS()
        {
            return instance;
        }

        #endregion

        #region Methods:

        /// <summary>
        /// Initializes the data structure.
        /// <para>Note: must be initialized when machine is loaded</para>
        /// </summary>
        /// <param name="stateMachine">The state machine</param>
        public void initializeDS(StateMachine stateMachine)
        {
            foreach (Transition transition in stateMachine.Transitions)
            {
                addTransition(transition.Target, transition);
            }
        }

        public void addTransition(State key, Transition value)
        {
            if (transitionDictionary.ContainsKey(key))
            {
                IList<Transition> transList = transitionDictionary[key] as List<Transition>;
                transList.Add(value);
            }
            else
            {
                IList<Transition> transList = new List<Transition>();
                transList.Add(value);
                transitionDictionary.Add(key, transList);
            }
        }

        public bool containsState(State key)
        {
            return transitionDictionary.ContainsKey(key);
        }

        public bool containsTransition(State key, Transition transition)
        {
            if (!containsState(key))
                return false;

            IList<Transition> transList = getInGoingTransitions(key);
            foreach (Transition trans in transList)
            {
                if (trans.Equals(transition))
                    return true;
            }
            return false;
        }

        public IList<Transition> getInGoingTransitions(State key)
        {
            return transitionDictionary[key] as IList<Transition>;
        }

        #endregion

    }
}
